package com.ljj;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class XmlParser extends DefaultHandler {

    /**
     * 当前节点名字
     */
    private String currentName;

    /**
     * 当前绝对深度
     */
    private Integer currentDeep = 0;

    /**
     * 当前节点txt值
     */
    private String currentValue;

    /**
     * 最后的返回结果
     */
    private Value root;

    private Value current;

    private String rootName;

    public XmlParser() {
        this.root = new Value(null, null);
    }

    public Value getResult() {
        return this.root;//.getValue(rootName).get();
    }

    //遍历xml文件开始标签
    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
        //System.out.println("sax解析开始");

    }

    //遍历xml文件结束标签
    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
        //System.out.println("sax解析结束");
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);
        //System.out.println("qName开始:" + qName + ";" + uri + ";" + localName);
        if (currentDeep == 0) {
            current = root;
            rootName = qName;
        }
        currentName = qName;
        currentDeep++;

        Value c = new Value(currentName, current);
        current.setValue(currentName, c);
        current = c;
        int num = attributes.getLength();
        for (int i = 0; i < num; i++) {
            String aName = attributes.getQName(i);
            String aValue = attributes.getValue(i);
            Value aO = new Value(aName, current);
            aO.setValue(aValue);
            current.setValue(aName, aO);
        }

    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName);
        //System.out.println("qName结束:" + qName + ";" + uri + ";" + localName);
        currentDeep--;
        current = current.getParent();
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);

        currentValue = new String(ch, start, length).trim();
        System.out.println("内容:" + currentValue + ";" + current.getPath() + ";" + start + ";" + length);
        /**
         * 有值则在当前节点直接放入值
         */
        if (!currentValue.equals("")) {
            current.setValue(currentValue);
        } else {

        }
    }
}